import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

export const getUserInfo = createAsyncThunk(
  'userInfo/getUserInfo',
  async () => {
    return {
      name: 'admin',
      age: 18,
    }
  }
)

const { name, reducer, actions } = createSlice({
  name: 'userInfo',
  initialState: {
    userInfo: {},
  },
  reducers: {
    setUserInfo(state, { payload }) {
      state.userInfo = payload
      localStorage.setItem('userInfo', JSON.stringify(payload))
    },
    getUserInfo(state) {
      state.userInfo = JSON.parse(localStorage.getItem('userInfo'))
    },
    clearUserInfo(state) {
      state.userInfo = {}
      localStorage.removeItem('userInfo')
    },
  },
  extraReducers: (builder) => {
    builder.addCase(getUserInfo.fulfilled, (state, { payload }) => {
      state.userInfo = payload
    })
  }
})

export default {
  name,
  reducer,
  actions: { ...actions }
}
